import "dart:convert";

import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/apartment/api.dart";
import "package:ct_pa_majordomo/pages/device/lock/api.dart";
import "package:ct_pa_majordomo/pages/device/lock/detail/index.dart";
import "package:ct_pa_majordomo/pages/device/lock/widgets/list_item.dart";
import "package:ct_pa_majordomo/pages/device/lock/widgets/search_layout/index.dart";
import "package:ct_pa_majordomo/pages/device/widgets/device_header.dart";
import "package:ct_pa_majordomo/router/keys.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:ct_pa_majordomo/widgets/empty_data/index.dart";
import "package:ct_pa_majordomo/widgets/filter_layout/index.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";
import "package:ct_pa_majordomo/pages/device/lock/widgets/search_layout/search_notifier.dart";

import "../../../widgets/filter_layout/filter_dropdown.dart";
import "../../../widgets/filter_layout/filter_header.dart";

class Lock extends StatefulWidget{
  const Lock({super.key});

  @override
  State<Lock> createState() => _LockState();

}

class _LockState extends State<Lock> {
  final SearchNotifier _controller = SearchNotifier();
  final ScrollController _scrollController = ScrollController();

  final List<FilterHeaderItem> _headerItems = [
    // FilterHeaderItem(title: "分组"),
    FilterHeaderItem(title: "状态"),
    FilterHeaderItem(
      title: "数量：0",
      render: (title) {
        return Text(
          title,
          textAlign: TextAlign.center,
          style: const TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.w500,
          ),
        );
      },
    ),
  ];
  final Map _filter = {"pageNum": 1,};
  List _groups = [];
  final List _lockStatus = [{"name": "全部"}, {"name": "未关联房间"}];
  List _lockList = [];
  int _total = 0;
  bool _isLoading = false;


  Future<void> _getGroups() async {
    try {
      // EasyLoading.show();
      List resData = await apartmentApi.getGroups();
      // EasyLoading.dismiss();
      setState(() => _groups = resData..insert(0, {"groupName": "全部"}));
    } catch (error) {
      print(error);
    }
  }
  
  Future<void> _getLockList() async {
    try {
      _isLoading = true;
      Map<String, dynamic> params = {};
      Map resData = await lockApi.getLockList(params);
      setState(() {
        _isLoading = false;
        _headerItems.last.title = "数量：${resData["total"] ?? 0}";
        _lockList.addAll(resData["rows"] ?? []);
        _total = resData["total"] ?? 0;
      });
    } catch (error) {
      print(error);
    }
  }

  Future<void> _refresh() async {
    _filter["pageNum"] = 1;
    _lockList = [];
    _getLockList();
  }

  void _onScroll() {
    if (_isLoading || _lockList.length >= _total) return;
    if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
      setState(() {
        _filter["pageNum"] += 1;
        _getLockList();
      });
    }
  }

  Widget _renderList() {
    if (_lockList.isNotEmpty) {
      return ListView.separated(
        controller: _scrollController,
        padding: const EdgeInsets.all(ThemeVars.paddingPage),
        physics: const AlwaysScrollableScrollPhysics(),
        itemBuilder: (context, index) {
          return GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              Stacker.pushNamed(Keys.DEVICE_LOCK_DETAIL, arguments: _lockList[index]).then((value) {
                if (value != null && value as bool) _refresh();
              });
            },
            child: ListItem(lock: _lockList[index],),
          );
        },
        separatorBuilder: (context, index) => const SizedBox(height: 15),
        itemCount: _lockList.length,
      );
    }
    return ListView(
      children: [
        EmptyData(),
      ],
    );
  }

  @override
  void initState() {
    super.initState();
    _getGroups();
    _getLockList();
    _scrollController.addListener(_onScroll);
  }

  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return DeviceHeader(
      title: "锁管理",
      leading: IconButton(
        icon: const Icon(Icons.arrow_back_ios_new),
        onPressed: () {
          Navigator.pop(context);
        },
      ),
      onSearch: (value) {
        setState(() {
          _filter["pageNum"] = 1;
          _filter["name"] = value;
        });
        _getLockList();
      },
      showFloatBtn: true,
      floatOnPress: () {
        Stacker.pushNamed(Keys.DEVICE_LOCK_ADD).then((refresh) {
          if (refresh != null && refresh as bool) {
            _refresh();
          }
        });
      },
      children: [
        FilterLayout(
          headerItems: _headerItems,
          dropdownItems: [
            // FilterDropdownItem(
            //   items: _groups,
            //   itemAsString: (item) => item["groupName"],
            //   compare: (item) => item["groupId"] == _filter["groupId"],
            //   onChanged: (item) => setState(() {
            //     _filter["groupId"] = item["groupId"];
            //   }),
            // ),
            FilterDropdownItem(
              items: _lockStatus,
              itemAsString: (item) => item["name"],
            ),
          ],
          child: RefreshIndicator(
            onRefresh: _refresh,
            child: _renderList(),
          ),
        ),
      ],
    );
  }

}